//
//  LXPhotoHelper.m
//  ZuLinProject
//
//  Created by bancheng on 2021/12/21.
//  Copyright © 2021 LX_App. All rights reserved.
//

#import "LXPhotoHelper.h"


#import "TZImagePickerController.h"

@interface LXPhotoDelegateHelper: NSObject<UIImagePickerControllerDelegate, UINavigationControllerDelegate>
@property (nonatomic, copy) LXPhotoCameraHelperBlock selectImageBlock;

@end

@interface LXPhotoHelper()<UIImagePickerControllerDelegate, UINavigationControllerDelegate,TZImagePickerControllerDelegate>
@property (nonatomic) LXPhotoHelperBlock block;
@property (nonatomic, strong) LXPhotoDelegateHelper *helper;
@property (nonatomic, copy) LXMultiplePhotoHelperBlock selectMultipleImageBlock;

@property (nonatomic, strong) NSMutableArray *selectedAssets;
@property (nonatomic) NSInteger num;
@end

static LXPhotoHelper *picker = nil;


@implementation LXPhotoHelper


+ (instancetype)shareHelper{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        picker = [[LXPhotoHelper alloc] init];
    });
    return picker;
}

- (void)showImageViewSelcteWithResultBlock:(LXPhotoHelperBlock)block{
    
   
    self.block = block;
    
    
    [Tool showSheetTitle:@"上传照片" msg:nil cancelTitle:@"取消" oneBtnTitle:@"拍照" twoBtnTitle:@"从手机相册选择" cancelHandlerBlock:^{
    } oneHandlerBlock:^{
        
        
        // 判断是否支持相机
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            
            NSUInteger sourceType = UIImagePickerControllerSourceTypeCamera;

            if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0){
                PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
                if (status == PHAuthorizationStatusDenied || status == PHAuthorizationStatusRestricted) {
                    //相册权限受限制
                    showAlert(@"请前往设置-隐私-相机-利行企业版-允许访问");
                    return;
                }
            }
            UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
            imagePickerController.modalPresentationStyle = 0;
            [imagePickerController.navigationBar setTintColor:[UIColor blackColor]];
            imagePickerController.delegate = self;
            imagePickerController.allowsEditing = NO;
            imagePickerController.sourceType = sourceType;
            [[BaseViewController getCurrentVC] presentViewController:imagePickerController animated:YES completion:^{}];
        }
        
    } twoHandlerBlock:^{
        
        NSInteger sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0){
            PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
            if (status == PHAuthorizationStatusDenied || status == PHAuthorizationStatusRestricted) {
                //相册权限受限制
                showAlert(@"请前往设置-隐私-相机-利行企业版-允许访问");
                return;
            }
        }
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
         imagePickerController.modalPresentationStyle = 0;
        [imagePickerController.navigationBar setTintColor:[UIColor blackColor]];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = NO;
        imagePickerController.sourceType = sourceType;
        [[BaseViewController getCurrentVC] presentViewController:imagePickerController animated:YES completion:^{}];
        

        
    } onVC:[BaseViewController getCurrentVC]];
    
    
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{}];
    UIImage *image=[info objectForKey:UIImagePickerControllerOriginalImage];
    
    UIImage *img = [self zipScaleWithImage:image];
    YLUploadMedia * imageM = [YLUploadMedia mediaWithType:YLUploadMediaTypeJpg mediaName:nil mimeName:@"file" obj:img];
    [self shanChuanImageWithArray:[NSMutableArray arrayWithObject:imageM]];
    
}

- (void)shanChuanImageWithArray:(NSMutableArray *)tmpAry{
    
    [MSNetworkManager postRevertUrl:POST_UploadFile_URL params:@{@"type":@"1"} formData:tmpAry success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
        if (isSuccess) {
            if (self.block) {
                self.block(resonseObj);
            }
        }
    } failure:^(NSUInteger code, NSString * _Nonnull message) {
        showAlert(@"网络异常,请稍后再试!");
    } withShowHud:YES];
    

}


-(UIImage *)zipScaleWithImage:(UIImage *)sourceImage{
    //进行图像尺寸的压缩
    CGSize imageSize = sourceImage.size;//取出要压缩的image尺寸
    CGFloat width = imageSize.width;    //图片宽度
    CGFloat height = imageSize.height;  //图片高度
    //1.宽高大于1280(宽高比不按照2来算，按照1来算)
    if (width>1280||height>1280) {
        if (width>height) {
            CGFloat scale = height/width;
            width = 1280;
            height = width*scale;
        }else{
            CGFloat scale = width/height;
            height = 1280;
            width = height*scale;
        }
    //2.宽大于1280高小于1280
    }else if(width>1280||height<1280){
        CGFloat scale = height/width;
        width = 1280;
        height = width*scale;
    //3.宽小于1280高大于1280
    }else if(width<1280||height>1280){
        CGFloat scale = width/height;
        height = 1280;
        width = height*scale;
    //4.宽高都小于1280
    }else{
    }
//进行尺寸重绘
    UIGraphicsBeginImageContext(CGSizeMake(width, height));
    [sourceImage drawInRect:CGRectMake(0,0,width,height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}


- (void)showImageViewSelcteWithResultBlock:(LXPhotoCameraHelperBlock)selectImageBlock andMultipleImageBlock:(LXMultiplePhotoHelperBlock)multipBlcok andSelectedNum:(NSInteger)num{
    self.num = num;
    [self showImageViewSelcteWithResultBlock:selectImageBlock andMultipleImageBlock:multipBlcok];
}

-(void)showImageViewSelcteWithResultBlock:(LXPhotoCameraHelperBlock)selectImageBlock andMultipleImageBlock:(LXMultiplePhotoHelperBlock)multipBlcok{
   
  
    
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction * canleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction * library = [UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        

            
            TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:self.num delegate:self];
        imagePickerVc.allowPickingVideo = NO;
            // 选中原图
            imagePickerVc.isSelectOriginalPhoto = YES;
            // 选满后置灰其他照片
            imagePickerVc.showPhotoCannotSelectLayer = YES;
            // 满屏
            imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
            // 序号
            imagePickerVc.showSelectedIndex = YES;
//            if (!ObjectIsEmpty(self.selectedAssets)) {
//                // 设置目前已经选中的图片数组
//                imagePickerVc.selectedAssets = self.selectedAssets; // 目前已经选中的图片数组
//            }
            [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
                self.selectedAssets = [NSMutableArray arrayWithArray:assets];
                NSMutableArray *imageAry = [NSMutableArray array];
                for (UIImage *image in photos) {
                    YLUploadMedia * imageM = [YLUploadMedia mediaWithType:YLUploadMediaTypeJpg mediaName:nil mimeName:@"file" obj:image];
                    [imageAry addObject:imageM];
                }
                
                
                if (multipBlcok) {
                    multipBlcok(imageAry);
                }
            }];
            [[BaseViewController getCurrentVC] presentViewController:imagePickerVc animated:YES completion:nil];
            

//        }
        
        
    }];
    UIAlertAction * carmare = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self isCanUseCamera:1];
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
            [self creatWithSourceType:UIImagePickerControllerSourceTypeCamera block:selectImageBlock];
        }else{
            NSLog(@"相机功能暂不能使用");
        }
    }];
    [alertController addAction:canleAction];
    [alertController addAction:carmare];
    [alertController addAction:library];
    
    [[[UIApplication sharedApplication] delegate].window.rootViewController presentViewController:alertController animated:YES completion:nil];

}
/**
 *  判断是否允许用系统相机
 */
- (void)isCanUseCamera:(NSInteger)type{
    /*
     typedef NS_ENUM(NSInteger, AVAuthorizationStatus) {
     AVAuthorizationStatusNotDetermined = 0,// 系统还未知是否访问，第一次开启相机时
     AVAuthorizationStatusRestricted, // 受限制的
     AVAuthorizationStatusDenied, //不允许
     AVAuthorizationStatusAuthorized // 允许状态
     } NS_AVAILABLE_IOS(7_0) __TVOS_PROHIBITED;
     */
    if (type == 1) {
        AVAuthorizationStatus authStatus =  [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied){
            
            UIAlertController *aler =[UIAlertController alertControllerWithTitle:@"该app相机权限被关闭" message:@"请到设置->隐私->打开该app相机服务" preferredStyle:UIAlertControllerStyleAlert];
            
            [aler addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
            }]];
            
            [aler addAction:[UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                if (@available(iOS 10.0, *)) {
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
                } else {
                    // Fallback on earlier versions
                }
            }]];
            
            UIViewController *vc =[[UIApplication sharedApplication] delegate].window.rootViewController;
            
            [vc presentViewController:aler animated:YES completion:nil];
            
            return;
            
        }
    } else {
        PHAuthorizationStatus authStatus = [PHPhotoLibrary authorizationStatus];
        if (authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied){
            
            UIAlertController *aler =[UIAlertController alertControllerWithTitle:@"该app相册权限被关闭" message:@"请到设置->隐私->打开该app相册服务" preferredStyle:UIAlertControllerStyleAlert];
            
            [aler addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
            }]];
            
            [aler addAction:[UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                if (@available(iOS 10.0, *)) {
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
                } else {
                    // Fallback on earlier versions
                }
            }]];
            
            UIViewController *vc =[[UIApplication sharedApplication] delegate].window.rootViewController;
            [vc presentViewController:aler animated:YES completion:nil];
            
            return;
            
        }
    }
    
}

- (void)creatWithSourceType:(UIImagePickerControllerSourceType)sourceType block:selectImageBlock{
    picker.helper                  = [[LXPhotoDelegateHelper alloc] init];
    picker.delegate                = picker.helper;
    picker.sourceType              = sourceType;
    picker.allowsEditing = NO;//默认是可以修改的

    picker.helper.selectImageBlock = selectImageBlock;

    [[[UIApplication sharedApplication] delegate].window.rootViewController presentViewController:self animated:YES completion:nil];
}


@end
@implementation LXPhotoDelegateHelper

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    
    [picker dismissViewControllerAnimated:YES completion:NULL];
    
}
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

    UIImage *image=[info objectForKey:UIImagePickerControllerOriginalImage];
    YLUploadMedia *imageM = [YLUploadMedia mediaWithType:YLUploadMediaTypeJpg mediaName:nil mimeName:@"file" obj:image];
    if (self.selectImageBlock) {
        self.selectImageBlock(@[imageM]);
    }
    [picker dismissViewControllerAnimated:YES completion:nil];
}

@end
